const { ErrorModel, SuccessModel } = require('../utils/index')
const logger = require('../utils/logger')
const { ChatPrivateMessageModel } = require('../models/chat_private_message')
const { ChatGroupMessageModel } = require('../models/chat_group_message')
const { ChatUserRelationModel } = require('../models/chat_user_relation')
const { ChatNewFriendsModel } = require('../models/chat_new_friends')
const { SysUser } = require('../models/sys_user')
const { ChatGroupInfoModel } = require('../models/chat_group_info')
const {
  ChatGroupUserRelationModel,
} = require('../models/chat_group_user_relation')
const { SocketModel } = require('../models/socket')
const e = require('express')

class DataChatsController {
  /**
   * @description 获取当前用户未读消息数量
   */
  static async unreadControl (req, res, next) {
    const { user_id } = req.user
    logger.info(`DataChatsController`, `unreadControl`, `user_id`, user_id)
    try {
      const unreadNum = await SocketModel.getAllUnread(user_id)
      logger.info(
        `DataChatsController`,
        `unreadControl`,
        `unreadNum`,
        unreadNum
      )
      res.json(new SuccessModel(unreadNum, `success`))
    } catch (error) {
      logger.error(`DataChatsController`, `unreadControl`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * @description 获取当前用户所有相关聊天信息列表
   */
  static async messageList (req, res, next) {
    const { user_id } = req.user
    logger.info(`DataChatsController`, `messageList`, `user_id`, user_id)
    try {
      const privateList = await ChatPrivateMessageModel.findByUserId(user_id)
      const groupList = await ChatGroupMessageModel.findByUserId(user_id)
      logger.info(
        `DataChatsController`,
        `messageList`,
        `privateList`,
        privateList
      )
      logger.info(`DataChatsController`, `messageList`, `groupList`, groupList)
      res.json(new SuccessModel({ privateList, groupList }, `success`))
    } catch (error) {
      logger.error(`DataChatsController`, `messageList`, `error`, error.message)
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * @description 获取私聊相关内容
   */
  static async getPrivateDetail (req, res, next) {
    const { limit, size = 1, to } = req.query
    const { user_id } = req.user
    logger.info(`DataChatsController`, `messageList`, `user_id`, user_id)
    try {
      const result = await ChatPrivateMessageModel.getHistoryMessage(
        to,
        user_id,
        limit,
        size
      )
      res.json(new SuccessModel(result, `success`))
    } catch (error) {
      logger.error(`DataChatsController`, `messageList`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * @description 保存私聊信息
   */
  static async saveMsg (req, res, next) {
    const { to, content, msg_type = 0, create_timestamp } = req.body
    const { user_id: from } = req.user
    logger.info(`DataChatsController`, `saveMsg`, `user_id`, from)
    try {
      await ChatPrivateMessageModel.save(from, to, content, msg_type, create_timestamp)
      res.json(new SuccessModel([], `success`))
    } catch (error) {
      logger.error(`DataChatsController`, `saveMsg`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * @description 是否是好友
   */
  static async isFriend (req, res, next) {
    const { other_user_id } = req.body
    const { user_id } = req.user
    if (!other_user_id) {
      res.json(new ErrorModel('', `获取不到好友信息`))
      return
    }
    logger.info(`DataChatsController`, `isFriend`, `user_id`, user_id)
    try {
      const result = await ChatUserRelationModel.check(user_id, other_user_id)
      if (result.length) {
        res.json(new SuccessModel({ check: false }, `success`))
      } else {
        res.json(new SuccessModel({ check: true }, `success`))
      }
    } catch (error) {
      logger.error(`DataChatsController`, `isFriend`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * @description 添加我的新好友通知
   */
  static async insertNewFriends (req, res, next) {
    let { to, content } = req.body
    const { user_id: from } = req.user
    logger.info(`DataChatsController`, `insertNewFriends`, `user_id`, from)
    try {
      const isFriend = await ChatUserRelationModel.check(from, to)
      if (isFriend.length) {
        res.json(new ErrorModel([], `已加为好友,请勿重复添加。`))
      }
      const findRes = await ChatNewFriendsModel.findByUserId(from, to)
      logger.info(`DataChatsController`, `insertNewFriends`, `findRes`, findRes)
      if (findRes.length) {
        const updateResult = await ChatNewFriendsModel.update(from, to, content)
        logger.info(
          `DataChatsController`,
          `insertNewFriends`,
          `updateResult`,
          updateResult
        )
      } else {
        const result = await ChatNewFriendsModel.insert(from, to, content)
        logger.info(`DataChatsController`, `insertNewFriends`, `result`, result)
      }
      res.json(new SuccessModel([], `success`))
    } catch (error) {
      logger.error(`DataChatsController`, `insertNewFriends`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * @description 获取新朋友通知
   */
  static async getNewFriends (req, res, next) {
    const { user_id: to } = req.user
    logger.info(`DataChatsController`, `getNewFriends`, `user_id`, to)
    try {
      const result = await ChatNewFriendsModel.find(to)
      logger.info(`DataChatsController`, `getNewFriends`, `result`, result)
      res.json(new SuccessModel(result, `success`))
    } catch (error) {
      logger.error(`DataChatsController`, `getNewFriends`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * @description 获取朋友列表
   */
  static async getFriends (req, res, next) {
    const { user_id } = req.user
    logger.info(`DataChatsController`, `getFriends`, `user_id`, user_id)
    try {
      const result = await ChatUserRelationModel.findAll(user_id)
      logger.info(`DataChatsController`, `getFriends`, `result`, result)
      res.json(new SuccessModel(result, `success`))
    } catch (error) {
      logger.error(`DataChatsController`, `getFriends`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * @description 获取好友聊天相关内容
   * @param {*} name
   */
  static async friendChatList (req, res, next) {
    const { limit = 10, size = 1, user_id: friend_id } = req.body
    const { user_id } = req.user
    logger.info(
      `DataChatsController`,
      `groupChatList`,
      `request`,
      limit,
      size,
      friend_id,
      user_id
    )
    try {
      if (!friend_id) {
        res.json(new ErrorModel([], `好友信息获取失败`))
      }
      const messageList = await ChatPrivateMessageModel.getHistoryMessage(
        user_id,
        friend_id,
        limit,
        size
      )
      res.json(new SuccessModel(messageList, 'success'))
    } catch (error) {
      logger.info(`DataChatsController`, `groupChatList`, `error`, error)
      res.json(new ErrorModel([], error.message))
      return
    }
  }

  /**
   * @description 加为好友
   */
  static async agreeBeFriend (req, res, next) {
    const { user_id, realname } = req.user
    const { from, content } = req.body
    logger.info(`DataChatsController`, `agreeBeFriend`, `user_id`, user_id)
    try {
      const agreeInfo = await ChatNewFriendsModel.updateStatus(from, user_id, 2)
      logger.info(
        `DataChatsController`,
        `agreeBeFriend`,
        `agreeInfo`,
        agreeInfo
      )
      const otherInfo = await SysUser.findOne(from)
      logger.info(
        `DataChatsController`,
        `agreeBeFriend`,
        `otherInfo`,
        otherInfo
      )

      const result = await ChatUserRelationModel.addRelation(
        user_id,
        realname,
        from,
        otherInfo.realname
      )
      logger.info(`DataChatsController`, `agreeBeFriend`, `result`, result)

      const sendMsg = await ChatPrivateMessageModel.save(from, user_id, content)
      logger.info(`DataChatsController`, `agreeBeFriend`, `sendMsg`, sendMsg)
      res.json(new SuccessModel([], `success`))
    } catch (error) {
      logger.error(`DataChatsController`, `agreeBeFriend`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * @description 拒绝加为好友
   */
  static async disagreeBeFriend (req, res, next) {
    const { user_id } = req.user
    const { from } = req.body
    logger.info(`DataChatsController`, `disagreeBeFriend`, `user_id`, user_id)
    try {
      const agreeInfo = await ChatNewFriendsModel.updateStatus(from, user_id, 1)
      logger.info(
        `DataChatsController`,
        `disagreeBeFriend`,
        `agreeInfo`,
        agreeInfo
      )
      res.json(new SuccessModel([], `success`))
    } catch (error) {
      logger.error(`DataChatsController`, `disagreeBeFriend`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * @description 删除好友
   */
  static async deleteFriend (req, res, next) {
    const { other_user_id } = req.body
    const { user_id } = req.user
    logger.info(`DataChatsController`, `deleteFriend`, `user_id`, user_id)
    try {
      await ChatUserRelationModel.delete(user_id, other_user_id)
      res.json(new SuccessModel([], `success`))
    } catch (error) {
      logger.error(`DataChatsController`, `deleteFriend`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * @description 修改好友备注
   */
  static async editorRemark (req, res, next) {
    const { other_user_id, other_user_alias } = req.body
    const { user_id } = req.user
    logger.info(`DataChatsController`, `editorRemark`, `user_id`, user_id)
    try {
      await ChatUserRelationModel.updateAlias(
        user_id,
        other_user_id,
        other_user_alias
      )
      res.json(new SuccessModel([], `success`))
    } catch (error) {
      logger.error(`DataChatsController`, `editorRemark`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * @description 查找群
   */
  static async findGroup (req, res, next) {
    const { group_name } = req.body
    const { user_id } = req.user
    logger.info(`DataChatsController`, `createGroup`, `user_id`, user_id)
    try {
      const result = await ChatGroupInfoModel.findByName(group_name)
      res.json(new SuccessModel(result, `success`))
    } catch (error) {
      logger.error(`DataChatsController`, `createGroup`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * @description 建群
   */
  static async createGroup (req, res, next) {
    const { group_name, group_notice, group_avatar } = req.body
    const { user_id, realname } = req.user
    logger.info(`DataChatsController`, `createGroup`, `user_id`, user_id)
    try {
      const result = await ChatGroupInfoModel.add(
        group_name,
        group_notice,
        group_avatar,
        user_id
      )
      await ChatGroupUserRelationModel.join(user_id, result.group_id, realname)
      res.json(new SuccessModel([], `success`))
    } catch (error) {
      logger.error(`DataChatsController`, `createGroup`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * @description 编辑群
   */
  static async editGroup (req, res, next) {
    const { group_name, group_notice, group_avatar, group_id } = req.body
    const { user_id } = req.user
    logger.info(`DataChatsController`, `editGroup`, `user_id`, user_id)
    try {
      await ChatGroupInfoModel.add(
        group_id,
        group_name,
        group_notice,
        group_avatar,
        user_id
      )
      res.json(new SuccessModel([], `success`))
    } catch (error) {
      logger.error(`DataChatsController`, `editGroup`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * @description 加群
   */
  static async joinGroup (req, res, next) {
    const { user_id, group_id } = req.body
    logger.info(`DataChatsController`, `joinGroup`, `user_id`, user_id)
    try {
      let memberLen = await ChatGroupUserRelationModel.findMemberId(group_id)
      if (memberLen > 50) {
        res.json(new ErrorModel([], '当前群的人数已达上限50人'))
      }
      let userGroup = await ChatGroupUserRelationModel.findMemberByUserId(
        group_id,
        user_id
      )
      if (userGroup.length) {
        res.json(new ErrorModel([], '你已加群,请勿重复加群'))
        return
      }
      const userInfo = SysUser.findOne(user_id)
      await ChatGroupUserRelationModel.join(
        group_id,
        user_id,
        userInfo.realname
      )
      res.json(new SuccessModel([], `success`))
    } catch (error) {
      logger.error(`DataChatsController`, `joinGroup`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * @description 退群
   */
  static async exitGroup (req, res, next) {
    const { user_id, group_id } = req.body
    logger.info(`DataChatsController`, `exitGroup`, `user_id`, user_id)
    try {
      await ChatGroupUserRelationModel.exit(group_id, user_id)
      res.json(new SuccessModel([], `success`))
    } catch (error) {
      logger.error(`DataChatsController`, `exitGroup`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * @description 获取群相关内容
   * @param {*} name
   */
  static async groupChatList (req, res, next) {
    const { limit = 10, size = 1, group_id } = req.body
    const { user_id } = req.user
    logger.info(
      `DataChatsController`,
      `groupChatList`,
      `request`,
      limit,
      size,
      group_id,
      user_id
    )
    try {
      if (!group_id) {
        res.json(new ErrorModel([], `群组信息获取失败`))
      }
      const groupMsg = await ChatGroupMessageModel.getList(
        group_id,
        limit,
        size,
        user_id
      )
      logger.info(`DataChatsController`, `groupChatList`, `groupMsg`, groupMsg)
      const groupInfo = await ChatGroupInfoModel.find(group_id)
      logger.info(
        `DataChatsController`,
        `groupChatList`,
        `groupInfo`,
        groupInfo
      )
      const groupMember = await ChatGroupUserRelationModel.findMemberId(
        group_id
      )
      logger.info(
        `DataChatsController`,
        `groupChatList`,
        `groupMember`,
        groupMember
      )
      const groupMemberInfo = await ChatGroupUserRelationModel.findMemberInfo(
        group_id
      )
      logger.info(
        `DataChatsController`,
        `groupChatList`,
        `groupMemberInfo`,
        groupMemberInfo
      )
      res.json(
        new SuccessModel(
          { groupMsg, groupInfo, groupMember, groupMemberInfo },
          'success'
        )
      )
    } catch (error) {
      logger.info(`DataChatsController`, `groupChatList`, `error`, error)
      res.json(new ErrorModel([], error.message))
      return
    }
  }

  /**
   * @description 保存群信息
   */
  static async saveGroupChat (req, res, next) {
    const { content, group_id } = req.query
    const { user_id } = req.user
    try {
      const groupMember = await ChatGroupUserRelationModel.findMemberId(
        group_id
      )
      await ChatGroupMessageModel.saveMsg(
        group_id,
        user_id,
        content,
        groupMember
      )
      res.json(new SuccessModel([], 'success'))
    } catch (error) {
      res.json(new ErrorModel([], error.message))
      return
    }
  }

  /**
   * @description 看某个用户是否在某个群中
   */
  static async isInGroup (req, res, next) {
    const { user_id, group_id } = req.query
    try {
      const groupMember = await ChatGroupUserRelationModel.findMemberByUserId(
        group_id,
        user_id
      )
      if (groupMember.length) {
        res.json(new SuccessModel({ isIn: true }, 'success'))
      } else {
        res.json(new SuccessModel({ isIn: false }, 'success'))
      }
    } catch (error) {
      res.json(new ErrorModel([], error.message))
      return
    }
  }

  /**
   * @description 获取群资料
   */
  static async getGroupInfo (req, res, next) {
    const { group_id, group_name } = req.query
    try {
      const result = await ChatGroupInfoModel.findInfoByNameOrId(
        group_id,
        group_name
      )
      res.json(new SuccessModel(result, 'success'))
    } catch (error) {
      res.json(new ErrorModel([], error.message))
      return
    }
  }

  /**
   * @description 获取群组列表
   */
  static async getGroups (req, res, next) {
    const { user_id } = req.user
    try {
      const result = await ChatGroupUserRelationModel.findByUserId(user_id)
      res.json(new SuccessModel(result, 'success'))
    } catch (error) {
      res.json(new ErrorModel([], error.message))
      return
    }
  }

  /**
   *
   */
  static async searchUserOrGroup (req, res, next) {
    const { user_id } = req.user
    const { search } = req.body
    logger.info(`DataChatsController`, `searchUserOrGroup`, `user_id`, user_id)
    logger.info(`DataChatsController`, `searchUserOrGroup`, `search`, search)
    try {
      const friendsList = await SysUser.findUser(user_id, search)
      logger.info(
        `DataChatsController`,
        `searchUserOrGroup`,
        `friendsList`,
        friendsList
      )
      const groupsList = await ChatGroupInfoModel.findGroup(user_id, search)
      logger.info(
        `DataChatsController`,
        `searchUserOrGroup`,
        `groupsList`,
        groupsList
      )
      res.json(new SuccessModel({ groupsList, friendsList }, 'success'))
    } catch (error) {
      res.json(new ErrorModel([], error.message))
      return
    }
  }

  /**
   *
   */
  static async clearNewFriendUnread (req, res, next) {
    const { user_id } = req.user
    logger.info(
      `DataChatsController`,
      `clearNewFriendUnread`,
      `user_id`,
      user_id
    )
    try {
      const result = await ChatNewFriendsModel.updateRead(user_id)
      logger.info(
        `DataChatsController`,
        `clearNewFriendUnread`,
        `result`,
        result
      )
      res.json(new SuccessModel([], 'success'))
    } catch (error) {
      res.json(new ErrorModel([], error.message))
      return
    }
  }

  /**
   *
   */
  static async clearUnread (req, res, next) {
    const { from } = req.body
    const { user_id: to } = req.user
    logger.info(
      `DataChatsController`,
      `clearUnread`,
      `user_id`,
      from, to
    )
    try {
      const result = await ChatPrivateMessageModel.clearUnread(from, to)
      logger.info(
        `DataChatsController`,
        `clearUnread`,
        `result`,
        result
      )
      res.json(new SuccessModel([], 'success'))
    } catch (error) {
      res.json(new ErrorModel([], error.message))
      return
    }
  }
}

module.exports = {
  DataChatsController,
}
